package com.steven.concurrency.example.sync;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * synchronized 是不可被中断的，适用于线程竞争不激烈的时候
 * lock 是可以被中断的，适用于线程竞争激烈，依然能保持常态
 * atomic 竞争激烈时维持常态比lock性能好，但是只能同步一个值
 */

public class Synchronized1 {



    public  void test1(){
        /**
         * 只作用当前调用对象
         */
        synchronized (this){
            for (int i = 0; i <10 ; i++) {
                System.out.println(i);
            }
        }
    }

    /**
     * 只作用当前调用对象
     */
    public  synchronized void test2(){
        for (int i = 0; i <10 ; i++) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        Synchronized1 synchronized1 = new Synchronized1();
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(()->{
            synchronized1.test2();
        });
        executorService.execute(()->{
            synchronized1.test2();
        });
    }
}
